//
//  ProgressGradientView.m
//  mcrmSAAS
//
//  Created by wjxfhxy on 15/10/20.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "ProgressGradientView.h"

static ProgressGradientView *s_view;

@implementation ProgressGradientView
{
    CAGradientLayer *_layer1;
//    CAGradientLayer *_layer2;
}

-(id)init
{
    self = [super initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].applicationFrame.size.width, 1)];
    
    _layer1 = [CAGradientLayer new];
    _layer1.frame = self.bounds;
    _layer1.colors = [NSArray arrayWithObjects:(id)[UIColor colorWithRed:1 green:1 blue:1 alpha:0.1].CGColor,(id)[UIColor whiteColor].CGColor,nil];
    _layer1.startPoint = CGPointMake(0, 0.5);
    _layer1.endPoint = CGPointMake(1, 0.5);

//    _layer2 = [CAGradientLayer new];
//    _layer2.frame = self.bounds;
//    _layer2.colors = [NSArray arrayWithObjects:(id)[UIColor colorWithRed:1 green:1 blue:1 alpha:0.1].CGColor,(id)[UIColor whiteColor].CGColor,nil];
//    _layer2.startPoint = CGPointMake(0, 0.5);
//    _layer2.endPoint = CGPointMake(1, 0.5);
////    [self.layer addSublayer:_layer1];
    
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    self.bottom = self.superview.height - 1;
}

-(void)start
{
    [self.layer addSublayer:_layer1];
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.duration = 5;
    animation.fromValue = @(-self.width);
    animation.toValue = @(self.width);
    animation.repeatCount = 10000;
    [_layer1 addAnimation:animation forKey:@"key"];
    
    self.alpha = 0;
    
    [UIView animateWithDuration:1 animations:^
    {
        self.alpha = 1;
    }];
}

-(void)stop:(void(^)())completion
{
    [UIView animateWithDuration:1 animations:^
    {
        self.alpha = 0;
    } completion:^(BOOL finished)
    {
        [_layer1 removeAnimationForKey:@"key"];
        completion();
    }];
}

+(void)start
{
    if(s_view == nil)
    {
        s_view = [ProgressGradientView new];
        UINavigationBar *bar = [XUINavigationController navigationController].navigationBar;
        [bar addSubview:s_view];
        
        [s_view start];
    }
}

+(void)stop
{
    ProgressGradientView *view = s_view;
    [s_view stop:^
    {
        [view removeFromSuperview];
    }];
    s_view = nil;
}

@end
